package apigateway.project.core.netty.processor;

import apigateway.project.core.context.GlobalContext;
import apigateway.project.core.context.HttpRequestWrapper;
import apigateway.project.core.filter.FilterChainFactory;
import apigateway.project.core.filter.GatewayFilterChain;
import apigateway.project.core.filter.GatewayFilterChainFactory;
import apigateway.project.core.helper.RequestHelper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpRequest;



/**
 * 核心流程的主执行逻辑
 */
public class NettyCoreProcessor implements NettyProcessor {

    @Override
    public void process(HttpRequestWrapper event) {
        ChannelHandlerContext ctx = event.getCtx();
        FullHttpRequest request = event.getFullHttpRequest();

        // 1. 解析fullhttprequest,将其转换为自己要的内部对象context
        GlobalContext globalContext = RequestHelper.buildContext(ctx, request);
        // 2. 执行整个过滤器逻辑: FilterChain
        GatewayFilterChain chain = GatewayFilterChainFactory.getGatewayFilterChainFactory().createChain(globalContext);
        try {
            chain.execute(globalContext);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //3.后续需要捕获自定义的异常，并且往channel写回错误
    }

    @Override
    public void start() {

    }

    @Override
    public void shutDown() {

    }
}
